<template>
  <div>
    <!-- 显示用户列表 -->
    <div v-for="user in users" :key="user.id" style="margin-top: 10px;">
      <button @click="startCall(user.id)">打给 {{ user.name }}</button>
    </div>

    <!-- 本地视频 -->
    <div id="local-player" style="width: 480px; height: 320px; background-color: rgba(0, 0, 0, 0.3);" v-if="callStarted"></div>

    <!-- 远程视频 -->
    <div v-for="remoteStream in remoteStreams" :key="remoteStream.getId()" style="margin-top: 10px;">
      <div :id="`remote-player-${remoteStream.getId()}`" style="width: 480px; height: 320px; background-color: rgba(0, 0, 0, 0.3);"></div>
    </div>
    
    <button @click="endCall" v-if="callStarted">结束通话</button> 
  </div>
</template>

<script>
import AgoraRTC from 'agora-rtc-sdk';

export default {
  data() {
    return {
      users: [
        { id: 1, name: '小明' },
        { id: 2, name: '小王' },
        // 添加其他用户
      ],
      remoteStreams: [],//存储远程视频流的数组。
      client: null, // 保存client对象、保存Agora客户端对象
      localStream: null, // 保存本地流对象
      status: 'idle', // 添加status属性
      callStarted: false, // 通话状态
    };
  },
  methods: {
    startCall(userId) {
      const appId = '8aaaa837064c4689982294ecbb0d587a'; 
      const token = '007eJxTYMjynvqTU8DtidNMf8WCX1NiRC/4ntcuOt/NIvfa/uyu+n8KDBaJQGBhbG5gZpJsYmZhaWlhZGRpkpqclGSQYmphnvhix8y0hkBGhmmyu5gZGSAQxOdkcEzPL0pMSc3NZ2AAAN+1IaA='; // 替换为您的Token
      const channelName = 'Agorademo'; // 频道名
      
      this.callStarted = true;

      // 初始化 Agora SDK
      const client = AgoraRTC.createClient({ mode: 'rtc', codec: 'vp8' });
      this.client = client; // 保存client对象
      client.init(appId, () => {
        console.log('AgoraRTC client initialized');
        
        // 使用静态密钥加入频道
        client.join(token, channelName, null, (uid) => {
          console.log('User ' + uid + ' join channel successfully');

          // 创建本地流
          const localStream = AgoraRTC.createStream({
            streamID: uid,
            audio: true,
            video: true,
            screen: false
          });

          this.localStream = localStream; // 保存本地流对象

          localStream.init(() => {
            console.log('Local stream initialized');
            localStream.play('local-player');

            // 发布本地流
            client.publish(localStream, (err) => {
              console.error('Publish local stream error: ' + err);
            });
          }, (err) => {
            console.error('Initialize local stream error: ' + err);
          });

          // 订阅新媒体
          client.on('stream-added', (evt) => {
            const stream = evt.stream;
            console.log('New stream added: ', stream.getId());
            client.subscribe(stream, (err) => {
              console.error('Subscribe stream failed', err);
            });
          });

          client.on('stream-subscribed', (evt) => {
            const remoteStream = evt.stream;
            console.log('Subscribed to remote stream: ', remoteStream.getId());
            this.remoteStreams.push(remoteStream);
            this.$nextTick(() => {
              remoteStream.play(`remote-player-${remoteStream.getId()}`);
            });
          });

          client.on('peer-leave', (evt) => {
            const remoteStream = evt.stream;
            const index = this.remoteStreams.findIndex(stream => stream.getId() === remoteStream.getId());
            if (index !== -1) {
              this.remoteStreams.splice(index, 1);
            }
          });
        }, (err) => {
          console.error('Join channel failed', err);
        });
      });

      client.on('error', (err) => {
        console.error('Agora RTC error: ', err);
      });
    },
    endCall() { 
      // 确保结束本地流和订阅的远程流
      if (this.client) {
        this.client.leave(() => {
          console.log("Left the channel successfully");

          // 停止并关闭本地流
          if (this.localStream) {
            this.localStream.stop();
            this.localStream.close();
          }

          // 停止并关闭所有远程流
          this.remoteStreams.forEach(stream => {
            stream.stop();
            stream.close();
          });
          
          this.remoteStreams = [];
          this.client = null;
          this.callStarted = false;
        }, (err) => {
          console.error("Leaving the channel failed", err);
        });
      }
    }
  },
  beforeDestroy() {
    this.endCall();
  }
};
</script>

<style scoped>
#local-player,
[id^="remote-player-"] {
  border: 1px solid #ccc;
  margin-top: 10px;
}
</style>